// export const BASE_URL = 'http://localhost:8080';

export const request = (url, method = 'GET', data = {}, header = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url, // 拼接 baseURL 和 接口路径
      method,
      data,
      header: {
        'content-type': 'application/json',
        Authorization: `Bearer ${wx.getStorageSync('access_token')}`,
        clientid: CLIENT_ID,
        ...header,
      },
      success(res) {
        if (res?.data?.code === 200) {
          resolve(res.data);
          return;
        }
        if (res?.data?.code === 401) {
          wx.navigateTo({ url: '/pages/login/index' });
          return;
        }
        wx.showToast({ title: '请求失败', icon: 'none' });
        reject(new Error(`网络错误: ${res.statusCode}`));
      },
      fail(err) {
        wx.showToast({ title: '网络异常', icon: 'none' });
        reject(err);
      },
    });
  });
};

export const upload = (url, filePath, name, fileName = '') => {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: `${BASE_URL}${url}`,
      filePath: filePath,
      name,
      formData: {
        originalName: fileName,
      },
      header: {
        Authorization: `Bearer ${wx.getStorageSync('access_token')}`,
        clientid: CLIENT_ID,
      },
      success: async res => {
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          resolve(data);
          return;
        }
      },
      fail: err => {
        wx.showToast({ title: '上传失败', icon: 'none' });
        reject(err);
      },
    });
  });
};

/**
 * 处理流式响应的请求函数
 * @param {string} url - 请求地址
 * @param {string} method - 请求方法，默认为 POST
 * @param {Object} data - 请求数据
 * @param {Function} onMessage - 处理消息的回调函数
 * @param {Function} onError - 处理错误的回调函数
 * @param {Function} onComplete - 完成时的回调函数
 * @param {Function} onReference - 处理引用数据的回调函数
 * @returns {Promise} 请求任务
 */
